import requests
import time
import jwt
from openai import images
def start(prompt):
    ak = "ABbeMJ3TaEe3tF8QEDfTMrKPaPP3dbr3" # 填写access key
    sk = "mQpRkkgELhHCMkhLfGeR8FCKyfaBeaGP" # 填写secret key
    #生成API_TOKEN
    def encode_jwt_token(ak, sk):
        headers = {
            "alg": "HS256",
            "typ": "JWT"
        }
        payload = {
            "iss": ak,
            "exp": int(time.time()) + 1800, # 有效时间，此处示例代表当前时间+1800s(30min)
            "nbf": int(time.time()) - 5 # 开始生效的时间，此处示例代表当前时间-5秒
        }
        token = jwt.encode(payload, sk, headers=headers)
        return token
    #获取生成的API_TOKEN
    api_token = encode_jwt_token(ak, sk)
    url='https://api-beijing.klingai.com/v1/images/generations'
    headers = {'Content-Type': 'application/json',
               'Authorization': f'Bearer {api_token}',
               }
    data={
        #model:kling-v1默认模型为kling-v1
        'prompt':prompt
    }
    res=requests.post(url,headers=headers,json=data)
    id=res.json()['data']['task_id']
    time.sleep(10)
    #使用id进行查询
    curl=f'https://api-beijing.klingai.com//v1/images/generations/{id}'
    headers = {'Content-Type': 'application/json',
               'Authorization': f'Bearer {api_token}',
               }
    cres=requests.get(curl,headers=headers)
    print(cres.text)
    time.sleep(2)
    img_url=cres.json()['data']['task_result']['images'][0]['url']
    print(img_url)
    #将文件保存到本地
    image=requests.get(img_url)
    id='可灵'+str(id)
    with open(f'static/images/{id}.jpg','wb') as f:
        f.write(image.content)
        f.close()
    return id